import type { TStartData } from "./type";
import PollingManager from "./PollingManager";
import { API_URL } from "./constant";

document.addEventListener("DOMContentLoaded", function () {
  const loginForm = document.getElementById("loginForm") as HTMLFormElement;
  const loginBtnWrapper = document.getElementById(
    "loginBtnWrapper"
  ) as HTMLFormElement;
  const username = document.getElementById("username") as HTMLInputElement;
  const password = document.getElementById("password") as HTMLInputElement;
  const passwordForm = document.getElementById(
    "passwordForm"
  ) as HTMLInputElement;
  const loginBtn = document.getElementById("loginBtn") as HTMLButtonElement;
  const startBtnElement = document.getElementById(
    "startBtn"
  ) as HTMLButtonElement;
  const versionElement = document.getElementById("version") as HTMLSpanElement;
  const shopSelectElement = document.getElementById(
    "shopSelect"
  ) as HTMLButtonElement;
  const panelContainerElement = document.getElementById(
    "panelContainer"
  ) as HTMLButtonElement;
  const platformSelectElement = document.getElementById(
    "platformSelect"
  ) as HTMLButtonElement;
  const multiplierMaxInputElement = document.getElementById(
    "multiplierMaxInput"
  ) as HTMLButtonElement;
  const multiplierMinInputElement = document.getElementById(
    "multiplierMinInput"
  ) as HTMLButtonElement;
  const activeTypeSelectElement = document.getElementById(
    "activeType"
  ) as HTMLSelectElement;
  const activeSimpleImageElement = document.getElementById(
    "activeSimpleImage"
  ) as HTMLAnchorElement;
  // 自动添加商品
  const addGoodsNumberInputElement = document.getElementById(
    "addGoodsNumberInput"
  ) as HTMLInputElement;
  const addGoodsCheckboxElement = document.getElementById(
    "addGoodsCheckbox"
  ) as HTMLInputElement;
  const onlyAddGoodsBtnElement = document.getElementById(
    "onlyAddGoodsBtn"
  ) as HTMLButtonElement;
  const pluginModeSelectElement = document.getElementById(
    "pluginMode"
  ) as HTMLSelectElement;
  const addGoodsNumberInput2Element = document.getElementById(
    "addGoodsNumberInput2"
  ) as HTMLInputElement;
  const priceSourceSelectElement = document.getElementById(
    "priceSourceSelect"
  ) as HTMLSelectElement;
  const priceSourceWrapperElement = document.getElementById(
    "priceSourceWrapper"
  ) as HTMLElement;
  const multiplierWrapperElement = document.getElementById(
    "multiplierWrapper"
  ) as HTMLElement;
  const multiplierMaxWrapperElement = document.getElementById(
    "multiplierMaxWrapper"
  ) as HTMLElement;
  const platformPricePercentageWrapperElement = document.getElementById(
    "platformPricePercentageWrapper"
  ) as HTMLElement;
  const platformPricePercentageInputElement = document.getElementById(
    "platformPricePercentageInput"
  ) as HTMLInputElement;

  function startAutoRegistration({
    isOnlyAddGoods,
  }: {
    isOnlyAddGoods: boolean;
  }) {
    const activeTypeValue = activeTypeSelectElement.value;
    const pluginMode = pluginModeSelectElement.value;
    const addGoodsNumber2 = Number(addGoodsNumberInput2Element.value);
    const priceSource = priceSourceSelectElement.value;
    const platformPricePercentage = parseFloat(
      platformPricePercentageInputElement.value
    );
    const isQuickMode = pluginMode === "quickMode";

    const data = {
      shopId: shopSelectElement.value,
      platform: platformSelectElement.value,
      multiplierMinInput: parseFloat(multiplierMinInputElement.value),
      multiplierMaxInput: parseFloat(multiplierMaxInputElement.value),
      activeType: activeTypeSelectElement.value,
      autoAddGoods:
        activeTypeValue === "selfPlatform"
          ? addGoodsCheckboxElement.checked
          : false,
      addGoodsNumber: Number(addGoodsNumberInputElement.value),
      addGoodsNumber2: isQuickMode ? addGoodsNumber2 : 0,
      isOnlyAddGoods,
      pluginMode,
      priceSource: isQuickMode ? priceSource : "erpPrice",
      platformPricePercentage:
        isQuickMode && priceSource === "platformPrice"
          ? platformPricePercentage
          : 0,
    };
    const errorMessage = checkStartData(data);
    if (errorMessage) {
      alert(errorMessage);
      return;
    }
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs && tabs[0] && tabs[0].id) {
        chrome.tabs.sendMessage(tabs[0]?.id, {
          action: "startAutoRegistration",
          data,
        });
      }
    });
  }
  onlyAddGoodsBtnElement.addEventListener("click", () => {
    startAutoRegistration({ isOnlyAddGoods: true });
  });

  activeTypeSelectElement.addEventListener("change", function (event) {
    const selectElement = event.target as HTMLInputElement;
    const value = selectElement.value;
    activeSimpleImageElement.href = `./icons/active-simple_${value}.png`;

    // 更新pluginMode选项状态
    initPluginModeOptions();

    // 更新auto-add-goods-wrapper的显示状态
    updateAutoAddGoodsWrapperVisibility();

    // 更新addGoodsNumberInput2的显示状态
    updateAddGoodsNumberInput2Visibility();

    // 更新价格来源的显示状态
    updatePriceSourceVisibility();
  });
  multiplierMinInputElement.addEventListener("change", function (event) {
    const inputElement = event.target as HTMLInputElement;
    const value = inputElement.value;
    const numericValue = parseFloat(value);
    if (!isNaN(numericValue)) {
      chrome.storage.sync.set({
        baoyiplus_multiplierMinInput: numericValue,
      });
    }
  });
  multiplierMaxInputElement.addEventListener("change", function (event) {
    const inputElement = event.target as HTMLInputElement;
    const value = inputElement.value;
    const numericValue = parseFloat(value);
    if (!isNaN(numericValue)) {
      chrome.storage.sync.set({
        baoyiplus_multiplierMaxInput: numericValue,
      });
    }
  });

  function initValueByStorage() {
    chrome.storage.sync
      .get(["baoyiplus_multiplierMinInput", "baoyiplus_multiplierMaxInput"])
      .then((data) => {
        const { baoyiplus_multiplierMinInput, baoyiplus_multiplierMaxInput } =
          data || {};
        if (baoyiplus_multiplierMinInput) {
          multiplierMinInputElement.value = baoyiplus_multiplierMinInput;
        }
        if (baoyiplus_multiplierMaxInput) {
          multiplierMaxInputElement.value = baoyiplus_multiplierMaxInput;
        }
      });
  }
  initValueByStorage();

  // 动态设置版本号
  if (versionElement) {
    let version = "";
    try {
      if (
        typeof chrome !== "undefined" &&
        chrome.runtime &&
        typeof chrome.runtime.getManifest === "function"
      ) {
        const manifest = chrome.runtime.getManifest();
        version = manifest?.version || "";
      }
    } catch (error) {
      console.warn("获取扩展版本号失败:", error);
    }
    if (version) {
      versionElement.textContent = `v${version}`;
    }
  }

  // 控制auto-add-goods-wrapper的显示/隐藏
  function updateAutoAddGoodsWrapperVisibility() {
    const autoAddGoodsWrapper = document.querySelector(
      ".auto-add-goods-wrapper"
    ) as HTMLElement;
    if (autoAddGoodsWrapper) {
      const activeTypeValue = activeTypeSelectElement.value;
      const pluginModeValue = pluginModeSelectElement.value;
      if (
        activeTypeValue === "selfPlatform" &&
        pluginModeValue === "visualizationMode"
      ) {
        autoAddGoodsWrapper.style.display = "flex";
      } else {
        autoAddGoodsWrapper.style.display = "none";
      }
    }
  }

  // 控制addGoodsNumberInput2的显示/隐藏
  function updateAddGoodsNumberInput2Visibility() {
    const addGoodsNumberInput2Wrapper =
      addGoodsNumberInput2Element?.parentElement as HTMLElement;
    if (addGoodsNumberInput2Wrapper) {
      const pluginModeValue = pluginModeSelectElement.value;
      if (pluginModeValue === "quickMode") {
        addGoodsNumberInput2Wrapper.style.display = "block";
      } else {
        addGoodsNumberInput2Wrapper.style.display = "none";
      }
    }
  }

  // 控制价格来源选择框的显示/隐藏
  function updatePriceSourceVisibility() {
    const pluginModeValue = pluginModeSelectElement.value;
    if (pluginModeValue === "quickMode") {
      priceSourceWrapperElement.style.display = "block";
    } else {
      priceSourceWrapperElement.style.display = "none";
    }
    // 更新倍率和百分比输入框的显示状态
    updateMultiplierAndPercentageVisibility();
  }

  // 控制倍率输入框和百分比输入框的显示/隐藏
  function updateMultiplierAndPercentageVisibility() {
    const pluginModeValue = pluginModeSelectElement.value;
    const priceSourceValue = priceSourceSelectElement.value;

    if (pluginModeValue === "quickMode") {
      if (priceSourceValue === "erpPrice") {
        // 根据ERP货源价格：显示倍率输入框，隐藏百分比输入框
        multiplierWrapperElement.style.display = "block";
        multiplierMaxWrapperElement.style.display = "block";
        platformPricePercentageWrapperElement.style.display = "none";
      } else if (priceSourceValue === "platformPrice") {
        // 根据平台价格：隐藏倍率输入框，显示百分比输入框
        multiplierWrapperElement.style.display = "none";
        multiplierMaxWrapperElement.style.display = "none";
        platformPricePercentageWrapperElement.style.display = "block";
      }
    } else {
      // 可视化模式：显示倍率输入框，隐藏百分比输入框
      multiplierWrapperElement.style.display = "block";
      multiplierMaxWrapperElement.style.display = "block";
      platformPricePercentageWrapperElement.style.display = "none";
    }
  }

  // 初始化pluginMode选项状态
  function initPluginModeOptions() {
    const activeTypeValue = activeTypeSelectElement.value;
    const quickModeOption = pluginModeSelectElement.querySelector(
      'option[value="quickMode"]'
    ) as HTMLOptionElement;

    if (["shop"].includes(activeTypeValue)) {
      // 如果当前是quickMode，改为visualizationMode
      if (pluginModeSelectElement.value === "quickMode") {
        pluginModeSelectElement.value = "visualizationMode";
      }
      // 禁用quickMode选项
      if (quickModeOption) {
        quickModeOption.disabled = true;
      }
    } else {
      // 如果不是shop，确保quickMode选项可用
      if (quickModeOption) {
        quickModeOption.disabled = false;
      }
    }
  }

  // 监听pluginMode的变化
  pluginModeSelectElement.addEventListener("change", function () {
    updateAddGoodsNumberInput2Visibility();
    updateAutoAddGoodsWrapperVisibility();
    updatePriceSourceVisibility();
  });

  // 监听价格来源的变化
  priceSourceSelectElement.addEventListener("change", function () {
    updateMultiplierAndPercentageVisibility();
  });

  // 初始化显示状态
  initPluginModeOptions();
  updateAutoAddGoodsWrapperVisibility();
  updateAddGoodsNumberInput2Visibility();
  updatePriceSourceVisibility();

  // 初始化检查登录状态
  checkLoginStatus();

  // 打开对话框的方法
  function openIPListDialog(data: any) {
    // 创建对话框背景
    const backdrop = document.createElement("div");
    backdrop.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      animation: fadeIn 0.3s;
  `;

    // 创建对话框内容
    const dialog = document.createElement("div");
    dialog.style.cssText = `
      background: white;
      width: 100%;
      max-height: 80vh;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      display: flex;
      flex-direction: column;
      animation: slideIn 0.3s;
  `;

    // 对话框标题
    const titleBar = document.createElement("div");
    titleBar.style.cssText = `
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      font-size: 16px;
  `;
    titleBar.textContent = "超出登录设备,请选择替换设备";

    // 关闭按钮
    const closeBtn = document.createElement("button");
    closeBtn.style.cssText = `
      background: none;
      border: none;
      cursor: pointer;
      font-size: 18px;
      color: #666;
  `;
    closeBtn.textContent = "×";
    closeBtn.onclick = () => document.body.removeChild(backdrop);
    titleBar.appendChild(closeBtn);

    // 表格容器
    const tableContainer = document.createElement("div");
    tableContainer.style.cssText = `
      overflow: auto;
      flex: 1;
  `;

    // 创建表格
    const table = document.createElement("table");
    table.style.cssText = `
      width: 100%;
      border-collapse: collapse;
      font-size: 14px;
  `;

    // 表头
    const thead = document.createElement("thead");
    thead.innerHTML = `
      <tr style="background: #f5f5f5;">
          <th style="text-align: left; border-bottom: 1px solid #eee; font-weight: bold;">IP地址</th>
          <th style="text-align: left; border-bottom: 1px solid #eee; font-weight: bold;">登录时间</th>
          <th style="text-align: left; border-bottom: 1px solid #eee; font-weight: bold;">操作</th>
      </tr>
  `;

    // 表体
    const tbody = document.createElement("tbody");

    // 添加数据行
    data.forEach((item: any, index: any) => {
      const tr = document.createElement("tr");
      tr.style.backgroundColor = index % 2 === 0 ? "#fff" : "#fafafa";
      tr.onmouseover = () => (tr.style.backgroundColor = "#f0f0f0");
      tr.onmouseout = () =>
        (tr.style.backgroundColor = index % 2 === 0 ? "#fff" : "#fafafa");

      tr.innerHTML = `
          <td style="border-bottom: 1px solid #eee;">${item.loginIp}</td>
          <td style="border-bottom: 1px solid #eee;">${item.createTime}</td>
          <td style="border-bottom: 1px solid #eee;">
              <button class="replace-btn" data-id="${item.id}" style="
                  margin-right: 8px;
                  background: #0078d7;
                  color: white;
                  border: none;
                  border-radius: 3px;
                  cursor: pointer;
              ">替换</button>
          </td>
      `;

      tbody.appendChild(tr);
    });

    // 如果没有数据
    if (data.length === 0) {
      const tr = document.createElement("tr");
      tr.innerHTML = `
          <td colspan="3" style="padding: 24px; text-align: center; color: #999; border-bottom: 1px solid #eee;">
              暂无数据
          </td>
      `;
      tbody.appendChild(tr);
    }

    // 组装表格
    table.appendChild(thead);
    table.appendChild(tbody);
    tableContainer.appendChild(table);

    // 底部按钮区
    const footer = document.createElement("div");
    footer.style.cssText = `
      border-top: 1px solid #eee;
      display: flex;
      justify-content: flex-end;
  `;

    const cancelBtn = document.createElement("button");
    cancelBtn.textContent = "关闭";
    cancelBtn.style.cssText = `
      background: #f5f5f5;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
  `;
    cancelBtn.onclick = () => document.body.removeChild(backdrop);
    footer.appendChild(cancelBtn);

    // 组装对话框
    dialog.appendChild(titleBar);
    dialog.appendChild(tableContainer);
    dialog.appendChild(footer);
    backdrop.appendChild(dialog);

    // 添加到页面
    document.body.appendChild(backdrop);

    // 添加动画样式
    const style = document.createElement("style");
    style.textContent = `
      @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
      }
      @keyframes slideIn {
          from { transform: translateY(-20px); opacity: 0; }
          to { transform: translateY(0); opacity: 1; }
      }
  `;
    backdrop.appendChild(style);

    // 绑定操作按钮事件
    backdrop.querySelectorAll(".replace-btn").forEach((btn) => {
      btn.addEventListener("click", (e: any) => {
        const id = e.currentTarget.getAttribute("data-id");
        handleLogin(id);
      });
    });
  }

  const handleLogoutRemoveToken = async () => {
    const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
    const { baoyiplus_accessToken = "" } = storage;
    const apiurl = `${API_URL}/api/user/logout`;
    return fetch(apiurl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + baoyiplus_accessToken,
      },
    });
  };
  const handleGetActivity = async () => {
    const storage = await chrome.storage.sync.get(["baoyiplus_accessToken"]);
    const { baoyiplus_accessToken = "" } = storage;
    const apiurl = `${API_URL}/api/user/commonLogin/getActivity`;
    return fetch(apiurl, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + baoyiplus_accessToken,
      },
    }).then((result) => {
      result.json().then(async (data) => {
        if (Number(data.code) === 401) {
          await clearLoginData();
          location.reload();
        }
      });
    });
  };
  const polling = new PollingManager(60 * 1000 * 10, handleGetActivity);

  loginForm.addEventListener("submit", async function (e) {
    e.preventDefault();
    await handleLogin();
  });

  function checkStartData(data: TStartData) {
    const {
      shopId,
      platform,
      multiplierMinInput,
      multiplierMaxInput,
      isOnlyAddGoods,
      pluginMode,
      priceSource,
    } = data;
    // 验证输入
    if (!platform) {
      return "请选择平台！";
    }
    if(pluginMode === "quickMode" && priceSource === "platformPrice") {
      return "";
    }
    if (!isOnlyAddGoods) {
      if (!shopId || shopId === "加载中...") {
        return "请选择店铺！";
      }
      if (isNaN(multiplierMinInput)) {
        return "请输入有效的最小倍率！";
      }
      if (multiplierMinInput <= 0) {
        return "最小倍率必须大于0！";
      }
      if (isNaN(multiplierMaxInput)) {
        return "请输入有效的最大倍率！";
      }
      if (multiplierMaxInput <= 0) {
        return "最大倍率必须大于0！";
      }
      if (multiplierMinInput > multiplierMaxInput) {
        return "最大倍率必须大于最小倍率";
      }
    }

    return "";
  }
  startBtnElement.addEventListener("click", () => {
    startAutoRegistration({ isOnlyAddGoods: false });
  });

  // 初始化店铺选择
  async function handleInitShopOptions(baoyiplus_accessToken: any) {
    try {
      shopSelectElement.disabled = true;
      const tempOption = document.createElement("option");
      tempOption.textContent = "加载中...";
      shopSelectElement.innerHTML = "";
      shopSelectElement.appendChild(tempOption);

      // 请求接口数据
      const response = await fetch(
        `${API_URL}/api/shop/commonData/selectList/shopInfo`,
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + baoyiplus_accessToken,
          },
        }
      );

      const responseData = await response.json();
      const data = responseData.data || [];

      // 清空并重新渲染options
      shopSelectElement.innerHTML = "";

      // 循环添加数据选项
      data.forEach((item: any) => {
        const option = new Option(item.shopName, item.id);
        shopSelectElement.appendChild(option);
      });

      const defaultValue = data?.[0]?.id || "";
      shopSelectElement.value = defaultValue;
      // 恢复select可用状态
      shopSelectElement.disabled = false;
    } catch (error) {
      console.error("渲染下拉选项失败:", error);

      // 显示错误状态
      shopSelectElement.innerHTML = "";
      const errorOption = new Option("加载失败", "");
      errorOption.disabled = true;
      shopSelectElement.appendChild(errorOption);
    }
  }

  // 检查登录状态函数
  async function checkLoginStatus() {
    const storage = await chrome.storage.sync.get([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
      "baoyiplus_username",
    ]);
    // 解构赋值，设置默认值防止undefined
    const {
      baoyiplus_accessToken = "",
      baoyiplus_expiresIn = 0,
      baoyiplus_username = "",
    } = storage;

    if (baoyiplus_accessToken) {
      const isExpired = checkTokenExpired(baoyiplus_expiresIn);
      if (!isExpired) {
        loginBtn.innerHTML = "登录成功";
        loginBtn.disabled = true;
        // 用户名输入框设置
        username.disabled = true;
        username.value = baoyiplus_username || "已登录用户";

        username.style.backgroundColor = "#f0f0f0"; // 视觉区分

        // 密码框设置
        passwordForm.style.display = "none";
        polling.start();
        if (!document.getElementById("logoutBtn")) {
          const logoutBtn = document.createElement("button");
          logoutBtn.id = "logoutBtn";
          logoutBtn.textContent = "退出登录";
          logoutBtn.style.marginLeft = "10px";
          logoutBtn.type = "button";
          logoutBtn.onclick = async () => {
            await handleLogoutRemoveToken();
            await clearLoginData();
            location.reload(); // 刷新页面恢复登录表单
            polling.stop();
          };
          loginBtnWrapper.appendChild(logoutBtn);
          panelContainerElement.classList.add("login-in");
          handleInitShopOptions(baoyiplus_accessToken);
        }
      } else {
        await clearLoginData();
        loginBtn.innerHTML = "登录已过期，请重新登录";
      }
    }
  }

  // 检查token是否过期（针对时间戳格式）
  function checkTokenExpired(expiresIn: string | number): boolean {
    if (!expiresIn) return true;

    // 统一转换为数字
    const expiryTime =
      typeof expiresIn === "string" ? parseInt(expiresIn) : expiresIn;

    // 获取当前时间戳（毫秒）
    const currentTime = new Date().getTime();
    return currentTime > expiryTime;
  }

  // 清除登录数据
  async function clearLoginData() {
    await chrome.storage.sync.remove([
      "baoyiplus_accessToken",
      "baoyiplus_expiresIn",
    ]);
    panelContainerElement.classList.remove("login-in");
  }

  // 处理登录逻辑
  async function handleLogin(logOutId = "") {
    loginBtn.disabled = true;
    loginBtn.innerHTML = "登录中...";

    try {
      const result = await login(username, password, logOutId);

      if (result?.code === 0 && result.data) {
        await chrome.storage.sync.set({
          baoyiplus_accessToken: result.data.accessToken,
          baoyiplus_expiresIn: result.data.expiresIn, // 存储原始时间戳
          baoyiplus_username: username.value,
        });
        panelContainerElement.classList.add("login-in");
        setTimeout(() => {
          handleInitShopOptions(result.data.accessToken);
        }, 500);
        showLoginSuccess();
      } else if (Number(result?.code) === 409) {
        const data: any = [];
        Object.keys(result.paramMap).forEach((key) => {
          data.push(result.paramMap[key]);
        });
        openIPListDialog(data);
      } else {
        showLoginError(result?.msg || "登录失败");
      }
    } catch (error) {
      console.error("登录异常:", error);
      showLoginError("网络异常");
    }
  }

  // 显示登录成功状态
  function showLoginSuccess() {
    loginBtn.innerHTML = "登录成功";
    loginBtn.disabled = true;
    location.reload();
  }

  // 显示登录错误状态
  function showLoginError(message: string) {
    loginBtn.innerHTML = message;
    loginBtn.style.color = "red";
    loginBtn.disabled = false;

    setTimeout(() => {
      loginBtn.innerHTML = "点击登录";
      loginBtn.style.color = "";
    }, 2000);
  }

  // 登录API
  async function login(
    user: HTMLInputElement,
    password: HTMLInputElement,
    logOutId: string = ""
  ) {
    const apiurl = `${API_URL}/api/user/login`;
    const params: any = {
      username: user.value,
      password: password.value,
      loginEntrance: "ACTIVITY_PLUGIN",
    };
    if (logOutId) {
      params.logOutId = logOutId;
      params.forceLogin = true;
    }
    const response = await fetch(apiurl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params),
    });
    return response.json();
  }
});
